<?php
/*
	异步支付通知处理
*/
define('NOSESSION',true);
require '../../core/core.php';
set_exi(function($message='success',$type='success'){
    //如果存在错误，此处整理错误日志，后期完善
    if($type=='error'){
        $log=date('Y/m/d H:i:s');
        $log.="\t{$_SESSION['uniacid']}\t{$_SESSION['uid']}\t{$message}\n";
        file_put_contents('error_log.txt',$log,FILE_APPEND);
    }
    echo 'error';
    exit;
});
if($_POST){
    $log2=ijson_encode($_POST);
    file_put_contents('error_log.txt',$log2."\n",FILE_APPEND);
    $bodydata=json_decode($_POST['data'],true);
    $body=$bodydata['body'];
}else{
    $body= $_RQ;
    $body['orderCode']= $body['out_order_no'];
    $body['totalAmount']= $body['pay_amount'];
    $body['payOrderCode']=$body['bank_order_no'];
    $body['tradeNo']=$body['bank_order_no'];
    $body['orderStatus']=$body['trade_status']=='SUCCESS'?1:0;
    $ishema=true;
}
file_put_contents('error_log.txt',$body['orderCode']."~~~~~~~~\n",FILE_APPEND);
$pay_order=pdo_get('core_paylog',array('tid'=>trim($body['orderCode'])));
if(!$pay_order){
    exi('指定订单不存在！'.$body['orderCode'],'error');
}
$payfee=$pay_order['fee']-$pay_order['di_fee'];
if($payfee!=$body['totalAmount']){
    $log=$pay_order['id'].'~'.$payfee.'~'.$body['totalAmount']."\n";
    file_put_contents('error_log.txt',$log,FILE_APPEND);
    //exi('订单金额不匹配！','error');
}
if($pay_order['status']!=0){
    exi('订单已支付！','error');
}
$_SESSION['uniacid']=$pay_order['uniacid'];
$_SESSION['uid']=$pay_order['mid'];
if($pay_order['merchid']){
    $_SESSION['onemerchid']=$pay_order['merchid'];
}
$_SESSION['this']='custom';
if($ishema){
    $check=model('jy_icbcpay/pay')->rsaCheckV2($body);
    $check=1;
    $pay_type='alipay';
}else{
    $check=model('jy_icbcpay/pay')->verify($_POST['data'],$_POST['sign']);
    $pay_type='wechat';
}
if($check){
    if($body['orderStatus']==1){
        //支付成功
        if($pay_order['di_credit'] && $pay_order['di_fee']>0){
            cfc('pay')->up_dipay($pay_order);
        }
        pdo_update('core_paylog',array('transaction_id'=>$body['payOrderCode'],'status'=>1,'pay_type'=>$pay_type,'paytime'=>time()),array('id'=>$pay_order['id']));
        $_SESSION['pay_result']=$_RQ['pay_result']=array('id'=>$pay_order['oid'],'transaction_id'=>$body['tradeNo'],'status'=>1,'pay_type'=>$pay_type,'fee'=>$pay_order['fee'],'pay_id'=>$pay_order['id'],'pay_tid'=>$pay_order['tid'],'title'=>$pay_order['title']);
        access($pay_order['back_url']);
        exi('SUCCESS','success');
    }
}else{
    exi('签名校验失败！','error');
}